//
//  ViewController.m
//  IOS -5day-3
//
//  Created by RIOS on 2018/4/12.
//  Copyright © 2018年 RIOS. All rights reserved.
//

#import "ViewController.h"

@interface ViewController () <UIScrollViewDelegate>
@property (weak, nonatomic) IBOutlet UIScrollView *vScrollVIew;
@property (weak, nonatomic) IBOutlet UIPageControl *vPageControl;
@property (nonatomic) int mWidth;
@property (weak,nonatomic) NSTimer *timer;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    [self setScrollView];
}

-(void)setScrollView{
    int width = self.vScrollVIew.frame.size.width;
    self.mWidth = width;
    int height = self.vScrollVIew.frame.size.height;
    int count = 5;
    self.vScrollVIew.contentSize = CGSizeMake(width*5, 0);
    self.vScrollVIew.showsVerticalScrollIndicator = false;
    self.vScrollVIew.showsHorizontalScrollIndicator = false;
    self.vScrollVIew.pagingEnabled = true;
    self.vScrollVIew.delegate = self;
    
    self.vPageControl.numberOfPages = 5;
    self.vPageControl.currentPage = 0;
   
    for (int i= 0; i < count; i++) {
        UIImageView *vImageView = [UIImageView new];
        vImageView.frame = CGRectMake(i*width, 0, width, height);
        vImageView.contentMode = UIViewContentModeScaleAspectFill;
        vImageView.clipsToBounds = true;
        [vImageView setImage:[UIImage imageNamed:[NSString stringWithFormat:@"icon%d",i+1]]];
        [self.vScrollVIew addSubview:vImageView];
        
    }
    [self createTimer];
    
    
}

-(void)createTimer{
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(autoScroll) userInfo:nil repeats:true];
    NSRunLoop *loop = [NSRunLoop currentRunLoop];
    [loop addTimer:self.timer forMode:NSRunLoopCommonModes];
}

-(void)autoScroll{
    NSLog(@"滚动了autoScroll");
    int offsetX = self.vScrollVIew.contentOffset.x;
    int page = (offsetX+ self.mWidth/2)/(self.mWidth) + 1 ;
    if ( page > 4 ) {
        page = 0;
    }
    [self.vScrollVIew setContentOffset:CGPointMake(page*self.mWidth, 0)  animated:true];
    
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
     NSLog(@"开始拖动了");
    [self.timer invalidate];
    self.timer = nil;
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    NSLog(@"结束拖动");
    [self createTimer];
}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    int offsetX = scrollView.contentOffset.x;
    int page = (offsetX+ self.mWidth/2)/(self.mWidth) ;
    self.vPageControl.currentPage = page;
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
